<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <title>拖拽图片示例</title>
  <style>
    body {
      position: relative;
      margin: 0;
      overflow: hidden;
      /* 确保超出部分不显示滚动条 */
    }

    .draggable {
      position: absolute;
      cursor: move;
      left: 100px;
      top: 100px;
    }

    #draggableImage {
      width: 200px;
      height: 200px;
    }
  </style>
</head>

<body>

  <div id="imgContainer" class="draggable">
    <img src="./fk.png" alt="Draggable Image" id="draggableImage" draggable="false">
  </div>

  <script>
    // 获取要拖拽的元素和图片元素
    const draggableElement = document.getElementById('imgContainer');
    const imgElement = document.getElementById('draggableImage');

    let offsetX, offsetY;
    let isDragging = false;

    // 获取浏览器窗口尺寸
    function getWindowSize() {
      return {
        width: window.innerWidth || document.documentElement.clientWidth,
        height: window.innerHeight || document.documentElement.clientHeight
      };
    }

    // 鼠标按下时的事件处理函数
    function handleMouseDown(e) {
      if (e.target.closest('#draggableImage')) { // 确保只对 img 元素生效
        isDragging = true;

        // 计算鼠标的相对偏移量
        offsetX = e.clientX - draggableElement.offsetLeft;
        offsetY = e.clientY - draggableElement.offsetTop;
      }
    }

    // 鼠标移动时的事件处理函数
    function handleMouseMove(e) {
      if (!isDragging) return;

      const winSize = getWindowSize();

      // 更新元素的位置，并进行边界检测
      let newLeft = e.clientX - offsetX;
      let newTop = e.clientY - offsetY;

      // 左边界
      if (newLeft < 0) newLeft = 0;
      // 右边界
      if (newLeft + draggableElement.offsetWidth > winSize.width)
        newLeft = winSize.width - draggableElement.offsetWidth;
      // 上边界
      if (newTop < 0) newTop = 0;
      // 下边界
      if (newTop + draggableElement.offsetHeight > winSize.height)
        newTop = winSize.height - draggableElement.offsetHeight;

      draggableElement.style.left = `${newLeft}px`;
      draggableElement.style.top = `${newTop}px`;
    }

    // 鼠标抬起时的事件处理函数
    function handleMouseUp() {
      isDragging = false;
    }

    // 添加事件监听器到整个文档，以便在任何地方都可以触发这些事件
    document.addEventListener('mousedown', handleMouseDown);
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);

    // 确保当用户在容器外点击并移动鼠标时不会触发拖拽
    draggableElement.addEventListener('mouseleave', handleMouseUp);

    // 取消默认的拖拽行为
    document.addEventListener('dragstart', function (event) {
      event.preventDefault();
    });

    // 如果需要支持触摸设备，也可以添加 touch 事件的处理
    draggableElement.addEventListener('touchstart', handleMouseDown, { passive: false });
    draggableElement.addEventListener('touchmove', handleMouseMove, { passive: false });
    draggableElement.addEventListener('touchend', handleMouseUp);
  </script>

</body>

</html>